package com.zhuhjay.boot.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.zhuhjay.constant.MessageConstant;
import com.zhuhjay.constant.RedisConstant;
import com.zhuhjay.domain.entity.Setmeal;
import com.zhuhjay.domain.http.PageResult;
import com.zhuhjay.domain.http.QueryPageBean;
import com.zhuhjay.domain.http.Result;
import com.zhuhjay.service.SetmealService;
import com.zhuhjay.utils.QiniuUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Objects;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhuhjay
 * @since 2022-04-02
 */
@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    private final StringRedisTemplate redisTemplate;

    @Reference
    private SetmealService setmealService;

    public SetmealController(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @PostMapping("/upload")
    public Result upload(@RequestPart("imgFile") MultipartFile file){
        try{
            String fileName = UUID.randomUUID().toString() +
                    Objects.requireNonNull(file.getOriginalFilename())
                            .substring(file.getOriginalFilename().lastIndexOf(".") - 1);
            QiniuUtils.upload2Qiniu(file.getBytes(), fileName);
            // 将此时被上传到七牛云的图片存储到redis中
            redisTemplate.opsForSet().add(RedisConstant.SETMEAL_PIC_RESOURCES, fileName);
            return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS, fileName);
        }catch (Exception e){
            return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
        }
    }

    @PostMapping
    public Result add(Integer[] ids, @RequestBody Setmeal setmeal){
        try{
            setmealService.add(ids, setmeal);
            return new Result(true, MessageConstant.ADD_SETMEAL_SUCCESS);
        }catch (Exception e){
            return new Result(false, MessageConstant.ADD_SETMEAL_FAIL);
        }
    }

    @PostMapping("/pageQuery")
    public Result queryPage(@RequestBody QueryPageBean queryPageBean){
        try{
            PageResult pageResult = setmealService.queryPage(queryPageBean);
            return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS, pageResult);
        }catch (Exception e){
            return new Result(false, MessageConstant.QUERY_SETMEAL_FAIL);
        }
    }

}
